package com.jxb.broker.store;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class IndexFile {

    private static String storeFile = "C:\\Users\\86177\\Documents\\learn\\rocketmq\\store\\index\\indexFile";

    /**
     *                 int absIndexPos =
     *                     IndexHeader.INDEX_HEADER_SIZE + this.hashSlotNum * hashSlotSize
     *                         + this.indexHeader.getIndexCount() * indexSize;
     *                 this.mappedByteBuffer.putInt(absIndexPos, keyHash);
     *                 this.mappedByteBuffer.putLong(absIndexPos + 4, phyOffset);
     *                 this.mappedByteBuffer.putInt(absIndexPos + 4 + 8, (int) timeDiff);
     *                 this.mappedByteBuffer.putInt(absIndexPos + 4 + 8 + 4, slotValue);
     *                 this.mappedByteBuffer.putInt(absSlotPos, this.indexHeader.getIndexCount());
     * @param args
     */

    public static void main(String[] args) {
        try (RandomAccessFile file = new RandomAccessFile(storeFile, "rw")) {
            FileChannel channel = file.getChannel();
            // 获取文件锁以确保文件在被写入时不被其他进程访问
            FileLock lock = channel.lock();
            try {
                // 将文件映射到内存中
                MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
                // 写入数据到内存映射区
                buffer.position(position);
                buffer.put(bytes);
                // 强制将缓冲区的数据写入文件，并清空缓冲区
                buffer.force();
                return position + bytes.length;
            } finally {
                // 释放文件锁
                lock.release();
                // 关闭文件通道
                channel.close();
                file.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
